//
//  CommitDetialCommitsViewController.swift
//  GiteeClient
//
//  Created by 王志标 on 2020/10/27.
//

import UIKit
import MJRefresh
import PKHUD
import UITableView_FDTemplateLayoutCell


/// 评论控制器
class CommitDetialCommitsViewController: BaseViewController {

   
    var noteTableView:UITableView!
    var cellID = "notecellid"
    var commitModel:CommitModel?
    var noteArray:[CommentModel]?
    var currentPage = 1
    
    var projectM:ProjectMdoel?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        
    }
    
    init(commit: CommitModel, project: ProjectMdoel) {
        super.init(nibName: nil, bundle: nil)
        self.commitModel = commit
        self.projectM = project
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        self.loadData(page: 1)
    }
}


// MARK: - 设置界面
extension CommitDetialCommitsViewController {
    
    func setupUI(){
        self.title = "评论"
        var fra = view.bounds
        fra.size.height -= Common.topHeight
        noteTableView = UITableView(frame: fra)
        noteTableView.register(UINib.init(nibName: "CommentTableViewCell", bundle: nil), forCellReuseIdentifier: cellID)
        view.addSubview(noteTableView)
        noteTableView.delegate = self
        noteTableView.dataSource = self
        noteTableView.separatorStyle = .none
        
        let mjH = MJRefreshNormalHeader {
            self.currentPage = 1
            self.loadData(page: self.currentPage)
        }
        mjH?.lastUpdatedTimeLabel.isHidden = true
        noteTableView.mj_header = mjH
        mjH?.beginRefreshing()
        
        let mjF = MJRefreshBackNormalFooter {
            self.currentPage += 1
            self.loadData(page: self.currentPage)
        }
        noteTableView.mj_footer = mjF
        
        
        noteTableView.emptyDataSetDelegate = self
        noteTableView.emptyDataSetSource = self
        
        if #available(iOS 13.0, *) {
            noteTableView.backgroundColor = Colors.backgroundColor
        }
    }
}


extension CommitDetialCommitsViewController {
    
    func loadData(page: Int){
        
        let url = URLs.V3URL + URLs.PROJECTS + self.projectM!.id.description + "/repository/commits/\( self.commitModel!.id!.description)/comment?page=\(self.currentPage)"
        
        /*
         NSString *strUrl = [NSString stringWithFormat:@"%@%@/%@/repository/commits/%@/comment",
                                                        GITAPI_HTTPS_PREFIX,
                                                        GITAPI_PROJECTS,
                                                        projectIdStr,
                                                        _commitID];
         
         NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithDictionary:@{
                                                                                           @"projectid"     : @(_projectID),
                                                                                           @"page"           : @(_page),
                                                                                           @"private_token" : [Tools getPrivateToken]
                                                                                           }];
         */
        
        // 异步加载
        DispatchQueue.global().async {
        
            let result:Result<[CommentModel?]> = NetWorkTool.shared.getArrayRequest(url: url, parameters: nil)
            
            DispatchQueue.main.async {
                if result.code == 0 {
                    if page == 1 {
                        self.noteArray = result.data as? [CommentModel]
                    }else {
                        self.noteArray?.append(contentsOf: (result.data as? [CommentModel])!)
                        if result.data?.count == 0 {
                            self.noteTableView.mj_footer.endRefreshingWithNoMoreData()
                            return
                        }
                    }
                    self.noteTableView.reloadData()
                }else {
                    HUD.flash(.label(result.message), delay: 2.0)
                }
                
                
                self.noteTableView.mj_header.endRefreshing()
                self.noteTableView.mj_footer.endRefreshing()
            }
        }
    }
}


extension CommitDetialCommitsViewController: UITableViewDelegate,UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        self.noteArray?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let model = self.noteArray![indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! CommentTableViewCell
        cell.model = model
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return tableView.fd_heightForCell(withIdentifier: cellID) { (cell) in
            
            (cell as! CommentTableViewCell).model = self.noteArray![indexPath.row]
        }
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        self.listViewDidScrollCallback?(scrollView)
    }
}

extension CommitDetialCommitsViewController: JXPagingViewListViewDelegate {
    public func listView() -> UIView {
        return self.view
    }
    
    public func listViewDidScrollCallback(callback: @escaping (UIScrollView) -> ()) {
        self.listViewDidScrollCallback = callback
    }

    public func listScrollView() -> UIScrollView {
        return self.noteTableView
    }
}

